/**
 * @file 授权管理
 * @date 2025/11/17 15:02:13
 * @author lyqjob@yeah.net
 */

import {  useState, useEffect, useMemo, useCallback  } from 'react';
import { Table, Button, Radio, Flex, Typography, Col, Divider, Modal, Space, Input, message } from 'antd';
import BindDataList from './components/BindDataList';
import { adminApi } from '@/services/admin';
import TableTransfer from './components/DataTransfer';
import AuthButton from '@/components/AuthButton';
import zhCN from 'antd/locale/zh_CN.js';
const { Text } = Typography;

const Authorization = () => {
    const [active, setActive] = useState('user');

    const [searchValue, setSearchValue] = useState('');
    const [searchInput, setSearchInput] = useState(''); // 新增：用于管理搜索输入框的值
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);


    const [usercurrent, setUserCurrent] = useState(1);
    const [rolecurrent, setRoleCurrent] = useState(1);
    const [userpageSize, setUserPageSize] = useState(10);
    const [rolepageSize, setRolePageSize] = useState(10);
    const [userTotal, setUserTotal] = useState(0);
    const [roleTotal, setRoleTotal] = useState(0);

    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [targetKeys, setTargetKeys] = useState([]);
    const [dataSource, setDataSource] = useState([]);
    const [bindRefresh, setBindRefresh] = useState(0);

    // 搜索
    const onSearch = useCallback((value) => {
        setLoading(true);
        setSearchValue(value || '');
        setSearchInput(value || ''); // 同步更新输入框的值
    }, []);

    const usercolumns = useMemo(() => ([
        {
            title: '编码',
            dataIndex: 'code',
            key: 'code',
            width: 150,
            fixed: 'left',
            eclipsis: true,
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 150,
            eclipsis: true,
        },
        {
            title: '部门',
            dataIndex: 'department_name',
            key: 'department_name',
            ellipsis: true,
            width: 150,
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
            width: 150,
        },
    ]), []);

    const rolecolumns = useMemo(() => ([
        {
            title: '编码',
            dataIndex: 'code',
            key: 'code',
            width: 150,
            fixed: 'left',
            eclipsis: true,
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 170,
        },
        {
            title: '部门',
            dataIndex: 'department_name',
            key: 'department_name',
            width: 150,
            ellipsis: true,
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true,
            width: 150,
            eclipsis: true,
        }
    ]), []);


    useEffect(() => {
        if (active === 'user') {
            getUserList(usercurrent, userpageSize, searchValue || '');
            return
        }
        getRoleList(rolecurrent, rolepageSize, searchValue || '');
    }, [active, searchValue])


    useEffect(() => {
        if (selectedRowKeys.length === 0) {
            return
        }
        if (active === 'user') {
            getUserBindRoles(selectedRowKeys[0], 1, rolepageSize);
            return
        }
        getRoleBindUsers(selectedRowKeys[0], 1, userpageSize);
    }, [selectedRowKeys, usercurrent, userpageSize, rolecurrent, rolepageSize, active])

    // 获取角色列表
    const getRoleList = useCallback(async (page, limit, searchvalue, istransfer) => {
        const [err, res] = await adminApi.getAllrole({ page, limit, searchvalue });
        if (err) {
            // message.warning('获取用户列表失败')
            setLoading(false);
        }
        if (res.code === 200 && res?.data?.data) {
            setLoading(false);
            if (istransfer) {
                res.data.data.forEach(item => {
                    item.key = item.id;
                    item.title = item.name;
                });
                setDataSource(res.data.data || []);
                return
            }
            setData(res.data.data);
            setRoleTotal(res.data.pagination.total)
            setDataSource(res.data.data || []);
        }
    }, []);

    // 获取用户列表
    const getUserList = useCallback(async (page, limit, searchvalue, istransfer) => {

        const [err, res] = await adminApi.getAlluser({ page, limit, searchvalue });
        if (err) {
            setLoading(false);
            return;
        }
        if (res.code === 200 && res?.data?.data) {

            setLoading(false);
            if (istransfer) {
                res.data.data.forEach(item => {
                    item.key = item.id;
                    item.title = item.name;
                });
                setDataSource(res.data.data || []);
                return
            }
            setData(res.data.data || []);
            setUserTotal(res.data.pagination.total)

        }
    }, []);

    // 分页改变时调用
    const onPageChange = useCallback((page, pageSize) => {
        setSelectedRowKeys([])         
        if (active === 'user') {
            setRoleCurrent(1)
            setUserCurrent(page);
            setUserPageSize(pageSize);
            getUserList(page, pageSize, searchValue || '');
        } else {
            setUserCurrent(1)
            setRoleCurrent(page);
            setRolePageSize(pageSize);
            getRoleList(page, pageSize, searchValue || '');
        }
    }, [active, searchValue, getUserList, getRoleList]);


    // 分页
    const rowSelection = useMemo(() => ({
        selectedRowKeys,
        onChange: (newSelectedRowKeys, _selectedRows) => {
            setSelectedRowKeys(newSelectedRowKeys);
        },
        getCheckboxProps: record => ({
            disabled: record.name === '超级管理员',
        }),
    }), [selectedRowKeys]);


    // 分配角色/用户
    const handleFunction = useCallback(async () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择用户/角色');
            return
        }
        if (active === 'user') {
            getRoleList(1, 1000, '', true)
            setModalVisible(true);
            return
        }
        getUserList(1, 1000, '', true)
        setModalVisible(true);
    }, [selectedRowKeys, active, getRoleList, getUserList]);

    // 表头
    const Header = () => {
        return (
            <Flex justify="space-between" align="center">
                <h3 style={{ margin: 0 }}>{active === 'user' ? '用户信息' : '角色信息'}</h3>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <AuthButton permission={['role:list', 'user:list', 'user:bind:roles', 'role:bind:users', 'user:view:roles', 'role:view:users']}>
                        <Button type="primary" onClick={() => handleFunction()}>
                            分配{active === 'user' ? '角色' : '用户'}
                        </Button>
                    </AuthButton>
                </div>
            </Flex>
        )
    }



    // 获取用户已绑定角色列表
    const getUserBindRoles = async (userid, page, limit) => {
        const [err, res] = await adminApi.getUserBindRoles(userid, { page, limit });
        if (err) {
            // message.error(err.message);
            return;
        }
        setTargetKeys(res?.data?.data?.map(item => item.id));
    }

    // 获取角色已绑定用户列表
    const getRoleBindUsers = async (roleid, page, limit) => {
        const [err, res] = await adminApi.getRoleBindUsers(roleid, { page, limit });
        if (err) {
            // message.error(err.message);
            return;
        }
        setTargetKeys(res?.data?.data?.map(item => item.id));
    }


    // 分配角色/用户 确认
    const onTransferChange = (nextTargetKeys, _direction, _moveKeys) => {
        setTargetKeys(nextTargetKeys);
    };

    // 切换按用户/角色
    const changeActive = useCallback((e) => {
        setActive(e.target.value);
        setSelectedRowKeys([]);
        setTargetKeys([]);
        setDataSource([]);
        
        setLoading(true);
        if (e.target.value === 'user') {
            getRoleList(1, 1000, '', true)
            return
        }
        getUserList(1, 1000, '', true)
    }, [getRoleList, getUserList]);

    // 确认绑定角色/用户
    const confirmBind = useCallback(async () => {
        // 绑定角色
        if (active === 'user') {
            const roleIds = targetKeys;
            if (roleIds.length === 0) {
                message.warning('至少保留一个角色');
                return
            }
            const [err,] = await adminApi.bindRoles({ userId: selectedRowKeys[0], roleIds: targetKeys });
            if (err) {
                // message.error(err.message);
                return;
            }
            message.success('绑定成功');
            setModalVisible(false);
            setBindRefresh(v => v + 1);
            return
        }
        const userIds = targetKeys;
        if (userIds.length === 0) {
            message.warning('至少保留一个用户');
            return
        }
        // 绑定用户
        const [err,] = await adminApi.bindUsers({ roleId: selectedRowKeys[0], userIds: targetKeys });
        if (err) {
            // message.error(err.message);
            return;
        }
        message.success('绑定成功');
        setModalVisible(false);
        setBindRefresh(v => v + 1);
    }, [active, targetKeys, selectedRowKeys, getUserBindRoles, getRoleBindUsers]);


    return (
        <div className="container">
            <Flex gap="middle" vertical>
                <Radio.Group value={active} onChange={e => changeActive(e)}>
                    <Radio value="user">按用户</Radio>
                    <Radio value="role">按角色</Radio>
                </Radio.Group>
                <Flex gap="middle" align="center" justify='flex-start'>
                    <Text>{active === 'user' ? '用户检索' : '角色检索'}：</Text>
                    <Space.Compact style={{ width: '30%' }}>
                        <Input 
                            allowClear 
                            value={searchInput}
                            placeholder={active === 'user' ? '用户编码/名称/手机号' : '角色编码/名称'} 
                            onChange={(e) => setSearchInput(e.target.value)}
                            onPressEnter={() => onSearch(searchInput)}
                        />
                        <Button type="primary" onClick={() => onSearch(searchInput)}>搜索</Button>
                    </Space.Compact>
                </Flex>
                <Flex flex={1} style={{ overflow: 'hidden' }}>
                    <Col span={12} >
                        <Table
                            locale={zhCN}
                            size="middle"
                            loading={loading}
                            title={Header}
                            columns={active === 'user' ? usercolumns : rolecolumns}
                            dataSource={data}
                            scroll={{ x: 800, y: 300 }}
                            rowKey="id"
                            rowSelection={{ type: 'radio', ...rowSelection }}
                            pagination={useMemo(() => ({
                                pageSize: active === 'user' ? userpageSize : rolepageSize,
                                current: active === 'user' ? usercurrent : rolecurrent,
                                showPage: true,
                                total: active === 'user' ? userTotal : roleTotal,
                                showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条`,
                                onChange: onPageChange
                            }), [active, usercurrent, userTotal, rolecurrent, roleTotal, onPageChange])}
                            onRow={(record, _index) => ({
                                onClick: (_event) => {
                                    if (record.is_protected === 1) {
                                        // message.warning('不能选择受保护用户');
                                        return;
                                    }
                                    setSelectedRowKeys([record.id]);
                                }
                            })}
                        />
                    </Col>
                    <Divider type="vertical" style={{ height: 400, backgroundColor: '#eee' }} />
                    <Col span={12} style={{ paddingRight: 10 }}>
                        <BindDataList
                            fetchList={useCallback(async (page, limit) => {
                                if (!selectedRowKeys?.[0]) {return { data: [], total: 0 }}
                                if (active === 'user') {
                                    const [err, res] = await adminApi.getUserBindRoles(selectedRowKeys[0], { page, limit });
                                    if (err) {return { data: [], total: 0 }}
                                    return { data: res?.data?.data || [], total: res?.data?.pagination?.total || 0 };
                                }
                                const [err, res] = await adminApi.getRoleBindUsers(selectedRowKeys[0], { page, limit });
                                if (err) {return { data: [], total: 0 }}
                                return { data: res?.data?.data || [], total: res?.data?.pagination?.total || 0 };
                            }, [active, selectedRowKeys])}
                            active={active}
                            id={selectedRowKeys?.[0]}
                            refresh={bindRefresh}
                            columns={active === 'user' ? rolecolumns : usercolumns}
                        />
                    </Col>
                </Flex>
            </Flex>
            <Modal
                title={'分配' + (active === 'user' ? '角色' : '用户')}
                open={modalVisible}
                onOk={() => confirmBind()}
                onCancel={() => setModalVisible(false)}
                style={{ width: 1200, height: 600 }}
                width={1200}
                height={600}
                destroyOnHidden


            >
                <TableTransfer
                    dataSource={dataSource}
                    targetKeys={targetKeys}
                    // disabled={disabled}
                    listDisabled={(record) => record.is_protected === 1}
                    // showSearch
                    // render={(item) => item.title}
                    showSelectAll={true}
                    onChange={onTransferChange}
                    // filterOption={filterOption}
                    leftColumns={useMemo(() => (active === 'user' ? rolecolumns.slice(0, 2) : usercolumns.slice(0, 2)), [active, rolecolumns, usercolumns])}
                    rightColumns={useMemo(() => (active === 'user' ? rolecolumns.slice(0, 2) : usercolumns.slice(0, 2)), [active, rolecolumns, usercolumns])}
                />
            </Modal>
        </div>

    )
}

export default Authorization;